package me.seawenc.db.migration.bean;

import com.alibaba.fastjson.JSONObject;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import me.seawenc.db.migration.bean.table.TableFieldBean;
import me.seawenc.db.migration.bean.table.TableRefBean;
import me.seawenc.db.migration.bean.table.TableIndexBean;
import me.seawenc.db.migration.bean.table.TablePartitionBean;
import me.seawenc.db.migration.helper.Optionalx;

public class TableBean {

    private String tableName;

    private String tableComment;

    private List<TableFieldBean> fields;
    // 外键
    private List<TableRefBean> refs;

    private List<TableIndexBean> indexs;

    private List<TablePartitionBean> partitions;

    /**
     * 是否有数据，Y，N
     */
    private String hasData;

    public TableBean() {

    }
    public TableBean(String tableName, List<JSONObject> ret) {
        //先去重，因为hive-spark sql返回有重复字段
        Map<String, TableFieldBean> map = ret.stream().map(row -> new TableFieldBean(row))
                .collect(Collectors.toMap(v -> v.getName(), v -> v, (v1, v2) -> v1));
        this.fields = map.values().stream().collect(Collectors.toList());
        this.tableName = tableName;
    }

    public boolean hasPrimaryKey() {
        boolean pkInFiled = fields.stream().anyMatch(v -> Optionalx.isPresent(v.getPriKey()));
        if(pkInFiled){
            return true;
        }
        if(Optionalx.isPresent(indexs)){
            return indexs.stream().anyMatch(v -> "Y".equals(v.getUniqueIndex()));
        }
        return false;
    }

    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public String getTableComment() {
        return tableComment;
    }

    public void setTableComment(String tableComment) {
        this.tableComment = tableComment;
    }

    public List<TableFieldBean> getFields() {
        return fields;
    }

    public void setFields(List<TableFieldBean> fields) {
        this.fields = fields;
    }

    public List<TableRefBean> getRefs() {
        return refs;
    }

    public void setRefs(List<TableRefBean> refs) {
        this.refs = refs;
    }

    public List<TableIndexBean> getIndexs() {
        return indexs;
    }

    public void setIndexs(List<TableIndexBean> indexs) {
        this.indexs = indexs;
    }

    public List<TablePartitionBean> getPartitions() {
        return partitions;
    }

    public void setPartitions(List<TablePartitionBean> partitions) {
        this.partitions = partitions;
    }
}
